winston = require 'winston'
path = require 'path'
fs = require 'fs'
util = require 'util'

_exists = (folder)->
	if fs.existsSync
		fs.existsSync folder
	else
		path.existsSync folder

_mkdir = (folder)->
	names = folder.split path.sep
	names.pop()
	parentFolder = names.join(path.sep)
	return if _exists folder
	if names.length is 1 or _exists parentFolder 
		return fs.mkdirSync folder
	else
		_mkdir parentFolder
		fs.mkdirSync folder
logs = {}
module.exports =
	getLogger:(name='master')->
		return logs[name] if logs[name]
		if __dirname.indexOf('release')>0
			filename = path.resolve("/data/logs/release" + __dirname.split('release')[1].replace(/\./g,'').replace(/\d/g,'') + "/../#{name}.log")
		else
			filename = path.resolve __dirname, "../logs/#{name}.log"
		folder = path.dirname filename
		unless _exists folder
			_mkdir folder
		logger = new winston.Logger
			transports: [
				new winston.transports.Console()
				new winston.transports.File
					filename: filename
					level: 'error'
					json: false
			]
		logger.logError = (err) ->
			if err
				logger.error err.stack ? util.inspect(err), {currentStack:new Error("").stack}

		logs[name] = logger
		logger